
import java.io.PrintWriter;
import java.util.HashMap;

class FunctionDeclaration extends Declaration {

	private Node ftype_;
	private Node type_;
	private Node block_;
	private Node formal_list_;
	private String name_;

	public FunctionDeclaration(Node f, Node t, Node fl, Node b, String n) {
		ftype_ = f;
		type_ = t;
		block_ = b;
		formal_list_ = fl;
		name_ = n;
	}

	public FunctionDeclaration(Node f, Node t, Node b, String n) {
		ftype_ = f;
		type_ = t;
		block_ = b;
		name_ = n;
	}

	@Override
	public void print(PrintWriter pw) {
		pw.println("Node name : FunctionDeclaration. Func name is: " + name_);
		// assert(type_ && block_);
		type_.print(pw);
		if (formal_list_ != null) {
			formal_list_.print(pw);
		}
		block_.print(pw);
	}
	
	public String translate(HashMap<String, PrintWriter> pws,  String strPare, SymbolTable rt, String parent) {
		String key = rt.getStack().get(1);
		PrintWriter pw = pws.get(key);
		String sc = "";
		
		for(int i = 1; i < rt.getStack().size(); i++) {
			if(i != rt.getStack().size() - 1) {
				sc += rt.getStack().get(i) + ";";
			} else {
				sc += rt.getStack().get(i);
			}
		}
		
		Symbol sy = new Symbol(name_, ftype_, true, sc, null);
		rt.getTables().add(sy);
		
		if(((FuncType) ftype_).getType().equals("def")){
			rt.getStack().push("function: " + name_);
			System.out.println("function pushed: " + name_);
			pw.print("public ");
			type_.translate(pws, "", rt, parent);
			pw.print(" "+name_);
			pw.print("(");
			if(formal_list_ != null){
				formal_list_.translate(pws, null, rt, parent);
			}
			pw.print(")");
			block_.translate(pws, null, rt, parent);
			
		} 
		else if (((FuncType) ftype_).getType().equals("def_timer")) {
			rt.getStack().push("function: " + name_);
			System.out.println("function pushed: " + name_);
			pw.print("    public ");
			type_.translate(pws, "", rt, parent);
			pw.print(" " + name_);
			pw.print("()");
			block_.translate(pws, null, rt, parent);
			pw.println("    public void " + name_ + "Timer() {");
			pw.println("        Timer timer = new Timer();");
			pw.println("        timer.schedule(new TimerTask() {");
			pw.println("            public void run() {");
			pw.println("                " + name_ + "();");
			pw.println("            }");
			pw.println("        }, 0, 3000");
			pw.println("    }");
			
		}
	 	return null;	
	}
}

